package com.lagou;

import com.lagou.handler.JSONSerializer;
import com.lagou.handler.MyHandler;
import com.lagou.handler.RpcDecoder;
import com.lagou.request.RpcRequest;
import com.lagou.util.IPUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServerBoot {

    private static int port = 9008;

    public static final String namespace = "/rpc";

    public static void main(String[] args) throws InterruptedException {
        //启动服务器
        startServer(IPUtil.getLocalAddress(), port);
        //注册到ZooKeeper服务器
        registerZk(port);
        SpringApplication.run(ServerBoot.class, args);
    }

    private static void startServer(String ip, int port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new MyHandler());
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(ip, port).sync();
    }

    private static void registerZk(int port){
        ZkClient zkClient = new ZkClient("39.108.102.154:2181");
        if(!zkClient.exists(namespace)){
            zkClient.createPersistent(namespace);
        }

        zkClient.createEphemeral(namespace + "/" + IPUtil.getLocalAddress() + ":" + port, 0L);
    }

}
